package com.daqsoft.service.system;

import com.daqsoft.data.project.Node;
import com.daqsoft.data.project.Project;
import com.daqsoft.data.project.Task;
import com.daqsoft.dto.PdfFontTypeEnum;
import com.daqsoft.util.DateUtil;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.font.TrueTypeFont;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.color.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.property.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * PDF服务层
 * @author 周麟东 on 11:49
 */
@Service
public class PDFService {
    @Value("${file.dir}")
    private String fileDir;
    /**
     * 将项目转换为PDF文档
     * @param project 项目对象
     * @return PDF文档对象
     */
    public Document parseProject(Project project) throws Exception {
        //字体风格
        Style bold = new Style();//字体加粗 用于标题
        bold.setProperty(Property.BOLD_SIMULATION,true);
        bold.setFontSize(16);

        Style text = new Style(); // 字体颜色 文本
        text.setMarginLeft(10);
        text.setFontSize(14);

        //创建PDF文档
        File file = new File(fileDir+File.separator+"doc"+File.separator+"project_out_doc_"+project.getId()+".pdf");
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));
        Document document = new Document(pdfDoc);
        document.setFont(createFont(PdfFontTypeEnum.YAHEI));

        //创建封面
        Image image = new Image(ImageDataFactory.create(fileDir+File.separator+"img"+File.separator+"logo.png")).setHeight(200).setHorizontalAlignment(HorizontalAlignment.CENTER); //封面图片 大旗logo
        document.add(image);
        Paragraph cn = new Paragraph("中科大旗软件有限公司\n\n\n\n\n").setFontSize(32).setTextAlignment(TextAlignment.CENTER);
        document.add(cn);
        cn = new Paragraph(project.getProjectName()+"简介\n\n\n").setFontSize(24).setTextAlignment(TextAlignment.CENTER);
        document.add(cn);
        cn = new Paragraph("项目经理 ： "+project.getPm().getRealName()).setFontSize(20).setTextAlignment(TextAlignment.CENTER);
        document.add(cn);

        //创建内容 :项目基础信息
        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        cn = new Paragraph("一、 项目基础信息 \n\n").addStyle(bold);
        document.add(cn);
        cn = new Paragraph("项目名称 ： "+project.getProjectName()).addStyle(text);
        document.add(cn);
        String time = "项目时间 ： "+ DateUtil.INS.parse(project.getStartDate(),"yyyy年MM月dd日")+" 至 "+ DateUtil.INS.parse(project.getAcceptance(),"yyyy年MM月dd日");
        cn = new Paragraph(time).setFontSize(14).addStyle(text);
        document.add(cn);
        cn = new Paragraph("项目编号 ： "+project.getProjectNum()).setFontSize(14).addStyle(text);
        document.add(cn);
        cn = new Paragraph("审核类型 ： "+getCheckType(project.getCheckType())).setFontSize(14).addStyle(text);
        document.add(cn);
        cn = new Paragraph("合同金额 ： ￥ "+project.getContractAmount()).setFontSize(14).addStyle(text);
        document.add(cn);
        cn = new Paragraph("合同工期 ： "+project.getTimeLimit()+"天").setFontSize(14).addStyle(text);
        document.add(cn);
        cn = new Paragraph("项目简介 ： "+project.getDesc()).setFontSize(14).addStyle(text);
        document.add(cn);
        //创建内容: 项目任务情况
        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        cn = new Paragraph("二、 任务完成情况 \n\n").addStyle(bold);
        document.add(cn);
        Table table = new Table(new float[]{6,2,3,3,3,3}).setWidth(UnitValue.createPercentValue(100));
        List<Cell> cells = createCells(project.getNodes());
        cells.forEach(table::addCell);
        document.add(table.setHorizontalAlignment(HorizontalAlignment.CENTER));

        document.close();

        return document;
    }

    private List<Cell> createCells(List<Node> nodes) {

        Style nodeText = new Style();
        nodeText.setFontSize(8);

        Style title = new Style();
        title.setFontSize(8);
        title.setBackgroundColor(new DeviceRgb(225,224,178));

        List<Cell> cells = new ArrayList<>();
        Cell cell1 = new Cell().add(new Paragraph("名称").addStyle(title));
        Cell cell2 = new Cell().add(new Paragraph("责任人").addStyle(title));
        Cell cell3 = new Cell().add(new Paragraph("计划开始时间").addStyle(title));
        Cell cell4 = new Cell().add(new Paragraph("实际开始时间").addStyle(title));
        Cell cell5 = new Cell().add(new Paragraph("计划结束时间").addStyle(title));
        Cell cell6 = new Cell().add(new Paragraph("实际结束时间").addStyle(title));
        cells.add(cell1);
        cells.add(cell2);
        cells.add(cell3);
        cells.add(cell4);
        cells.add(cell5);
        cells.add(cell6);
        for (Node node : nodes) {
            cell1.add(new Paragraph(node.getName()).addStyle(nodeText));
            cell2.add(new Paragraph("\n").addStyle(nodeText));
            cell3.add(new Paragraph(DateUtil.INS.parse(node.getStartDate())).addStyle(nodeText));
            cell4.add(new Paragraph("\n").addStyle(nodeText));
            cell5.add(new Paragraph(DateUtil.INS.parse(node.getEndDate())).addStyle(nodeText));
            cell6.add(new Paragraph("\n").addStyle(nodeText));
            addTaskToCell(cells,node.getTasks(),nodeText);
        }
        return cells;
    }

    private void addTaskToCell(List<Cell> cells, List<Task> tasks , Style nodeText) {
        Style taskText = new Style();
        taskText.setFontSize(8);
        taskText.setMarginLeft(15);

        for (Task task : tasks) {
            if (task.getChildren() == null){
                taskText.setMarginLeft(25);
            }
            cells.get(0).add(new Paragraph(task.getName()).addStyle(taskText));
            cells.get(1).add(new Paragraph(task.getPrincipal().getRealName()).addStyle(nodeText));
            cells.get(2).add(new Paragraph(DateUtil.INS.parse(task.getStartDate())).addStyle(nodeText));
            if (task.getRealStartDate()!= null){
                cells.get(3).add(new Paragraph(DateUtil.INS.parse(task.getRealStartDate())).addStyle(nodeText));
            }else {
                cells.get(3).add(new Paragraph("尚未开始").addStyle(nodeText));
            }
            cells.get(4).add(new Paragraph(DateUtil.INS.parse(task.getEndDate())).addStyle(nodeText));
            if (task.getRealEndDate()!= null){
                cells.get(5).add(new Paragraph(DateUtil.INS.parse(task.getRealEndDate())).addStyle(nodeText));
            }else {
                cells.get(5).add(new Paragraph("尚未结束").addStyle(nodeText));
            }
            if (task.getChildren()!=null){
                addTaskToCell(cells,task.getChildren(),nodeText);
            }
        }
    }

    /**
     * 创建PDF字体
     * @param typeEnum 字体类型 目前支持微软雅黑和方正兰亭超细黑简体
     * @return PDF对象
     */
    private PdfFont createFont(PdfFontTypeEnum typeEnum) {
        try {
            if (typeEnum == PdfFontTypeEnum.LIGHT) {
                TrueTypeFont font = new TrueTypeFont(fileDir+File.separator+"font"+File.separator+"FZLTCXHJW.ttf");
                return PdfFontFactory.createFont(font, PdfEncodings.IDENTITY_H, false);
            }else if(typeEnum == PdfFontTypeEnum.YAHEI){
                TrueTypeFont font = new TrueTypeFont(fileDir+File.separator+"font"+File.separator+"MicrosoftYaHeiLight.ttf");
                return PdfFontFactory.createFont(font, PdfEncodings.IDENTITY_H, false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getCheckType(int checkType){
        switch (checkType){
            case 0 : return "质量内审";
            case 1 : return "质量外审（有监理）";
            case 2 : return "质量外审（无监理）";
        }
        return checkType+"";
    }
}
